package com.qyl.socket_upload.server;

import com.alibaba.fastjson.JSONObject;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Map;

public class FileServer {
    public static final int PORT = 8888;
    public static final String PATH = "E:\\";

    public void start() throws Exception {
        System.out.println("start...");
        //创建服务器端对象
        ServerSocket server = new ServerSocket(PORT);
        while(true) {
            try {
                Socket socket = server.accept();
                //创建文件输出流和网络输入流
                DataInputStream in = new DataInputStream(socket.getInputStream());
                String res = in.readUTF();
                System.out.println("拿到的数据："+res);
                Map<String, Object> map = JSONObject.parseObject(res);
                //读取client发来的文件名，创建文件输出流
                File file = new File(PATH + map.get("fileName"));
                FileOutputStream out = new FileOutputStream(file);
                byte[] buffer = new byte[1024];
                while (true) {
                    System.out.println("接收文件长度： "+file.length()+"    "+(int)map.get("contentType"));
                    if((int)map.get("contentType") == file.length()){
                        out.close();
                        break;
                    }
                    out.write(buffer, 0, in.read(buffer));
                }
                System.out.println("服务器保存完毕！");
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) throws Exception {
        new FileServer().start();
    }
}
